<template>
  <div class="tree-node">
    <div class="tree-empty" v-if="isEmpty">
      {{ emptyText }}
    </div>
    <div v-else class="tree-content">
      <tree-node-item
        v-for="item in root.childNodes"
        :key="item.id"
        :item="item"
        @node-item-click="nodeItemClick"
      />
    </div>
  </div>
</template>
<script>
import TreeNodeItem from "./TreeNodeItem.vue";
import Bus from "./state/bus";
import Node from "./state/node";
import Meta from "./state/meta";
export default {
  name: "TreeNode",
  components: { TreeNodeItem },
  props: {
    node: {
      type: Array,
      required: true,
    },
    nodeKey: {
      type: String,
      required: true,
    },
    labelKey: {
      type: String,
      default: "label",
    },
    childrenKey: {
      type: String,
      default: "children",
    },

    emptyText: {
      type: String,
      required: false,
      default: "暂无数据",
    },
    expandAll: {
      type: Boolean,
    },
    expandedKeys: Array,
  },
  methods: {
    initData() {
      var meta = new Meta({
        key: this.nodeKey,
        label: this.labelKey,
        children: this.childrenKey,
        expandAll: this.expandAll,
      });
      var root = new Node({ id: "0", [meta.children]: this.node }, meta);
      this.root = root;
    },
    nodeItemClick(node) {
      this.$emit("node-item-click", node);
    },
  },
  data() {
    return { root: undefined };
  },
  created() {
    this.isTree = true;
    Bus.$on("node-item-click", (node) => {
      this.$emit(node);
    });
  },
  watch: {
    node() {
      this.initData();
    },
  },

  computed: {
    isEmpty() {
      return this.node.length == 0;
    },
  },
};
</script>
